use hostname;
use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct User {
    pub name: String,
    pub ip: Vec<String>,
}

pub struct ServiceDiscovery {
    mdns: ServiceDaemon,
    current_service: Option<ServiceInfo>,
    users: Arc<Mutex<HashMap<String, User>>>,
    port: u16,
    self_name: String,
    service_type: String,
}

impl ServiceDiscovery {
    pub fn new(
        service_type: &str,
        self_name: &str,
        ip: &str,  // 自己的ip地址
        port: u16, // 自己要监听的端口
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let mdns = ServiceDaemon::new()?;

        let full_service_type = format!("_{}._tcp.local.", service_type);
        let hostname = format!("{}.local.", hostname::get()?.to_string_lossy());

        let property: Vec<(String, String)> = Vec::new();
        let mut ips: HashSet<IpAddr> = HashSet::new();
        ips.insert(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10)));
        let service_info = ServiceInfo::new(
            &full_service_type,
            self_name,
            &hostname,
            ip,
            port,
            &property[..],
        )?;

        mdns.register(service_info.clone())?;

        Ok(Self {
            mdns,
            current_service: Some(service_info),
            users: Arc::new(Mutex::new(HashMap::new())),
            port,
            self_name: self_name.to_string(),
            service_type: full_service_type,
        })
    }

    pub fn start(&mut self) {
        let receiver = self
            .mdns
            .browse(&self.service_type)
            .expect("Failed to start browsing");
        let users = self.users.clone();
        let self_name = self.self_name.clone();
        thread::spawn(move || {
            println!("start listen");
            while let Ok(event) = receiver.recv() {
                match event {
                    ServiceEvent::ServiceResolved(info) => {
                        println!("new connect: {:?}", info);
                        let fullname = info.get_fullname().to_string();
                        let initial_name = match fullname.find('.') {
                            Some(index) => &fullname[..index],
                            None => &fullname,
                        };
                        if initial_name == &self_name {
                            continue;
                        }
                        let mut users = users.lock();
                        if let Some(user) = users.get_mut(initial_name) {
                            // 更新现有用户的 IP 地址，仅包含 IPv4
                            user.ip = info
                                .get_addresses()
                                .iter()
                                .filter(|ip| ip.is_ipv4())
                                .map(|ip| ip.to_string())
                                .collect();
                        } else {
                            // 添加新用户，仅包含 IPv4 地址
                            let address: Vec<String> = info
                                .get_addresses()
                                .iter()
                                .filter(|ip| ip.is_ipv4())
                                .map(|ip| ip.to_string())
                                .collect();
                            users.insert(
                                initial_name.to_string(),
                                User {
                                    name: initial_name.to_string(),
                                    ip: address,
                                },
                            );
                            println!("{:?}", users);
                        }
                    }
                    ServiceEvent::ServiceRemoved(service_type, fullname) => {
                        println!(
                            "service removed, service_type: {}, fullname: {}",
                            service_type, fullname
                        );
                        let initial_name = match fullname.find('.') {
                            Some(index) => &fullname[..index],
                            None => &fullname,
                        };
                        let mut users = users.lock();
                        users.remove(initial_name);
                    }
                    _ => {}
                }
            }
            println!("stop daemon");
        });
    }

    pub fn get_users(&self) -> Vec<User> {
        let users = self.users.lock();
        let mut result = Vec::new();
        users
            .iter()
            .filter(|item| item.0 != &self.self_name)
            .for_each(|item| {
                result.push(item.1.clone());
            });
        result
    }

    pub fn stop(&mut self) {
        let full_service_type = self.service_type.clone();
        self.mdns.stop_browse(&full_service_type);
        if let Some(service) = self.current_service.take() {
            // 显式发送 Goodbye 包，TTL 设为 0 表示服务下线
            if let Err(e) = self.mdns.unregister(&service.get_fullname()) {
                eprintln!("Error unregistering service: {}", e);
            }
            // 短暂延迟确保发送完成（根据实际情况调整）
            thread::sleep(Duration::from_millis(100));
        }
    }
}

impl Drop for ServiceDiscovery {
    fn drop(&mut self) {
        self.stop();
        // 确保 ServiceDaemon 正确关闭，释放资源
        if let Err(e) = self.mdns.shutdown() {
            eprintln!("Error shutting down mDNS daemon: {}", e);
        }
    }
}
